package tgc.rj.zz.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.rj.zz.custom.DataGridUtils;
import tgc.rj.zz.entity.Accredit;
import tgc.rj.zz.entity.Invoice;
import tgc.rj.zz.entity.Journal;
import tgc.rj.zz.entity.Lessee;
import tgc.rj.zz.entity.LesseeAdmin;
import tgc.rj.zz.entity.SysUser;
import tgc.rj.zz.form.AccreditForm2;
import tgc.rj.zz.form.InvoiceForm;
import tgc.rj.zz.form.LesseeForm;
import tgc.rj.zz.form.VerifyCodeUtils;
import tgc.rj.zz.security.UserUtils;
import tgc.rj.zz.service.AccreditService;
import tgc.rj.zz.service.InvoiceService;
import tgc.rj.zz.service.JournalService;
import tgc.rj.zz.service.LesseeAdminService;
import tgc.rj.zz.service.LesseeService;
import tgc.rj.zz.service.SysUserService;

@Controller
@RequestMapping(value="/lessee")
public class LesseeController {
	@Autowired
	private LesseeService lesseeDAO;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private LesseeAdminService lesseeAdminDAO;
	@Autowired
	private InvoiceService invoiceService;
	@Autowired
	private SysUserService userDAO;
	@Autowired
	private AccreditService accService;
	@Autowired
	private JournalService service;

	
	@Value("${spring.mail.username}")
	private String mailusername;
	@Autowired
	JavaMailSender jms;
	
	/**
	 * 租户管理
	 * @return
	 */
	@RequestMapping(value="/all")
	public String all() {
		return "system/lessee";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(LesseeForm form) {
		Pageable pageable = form.buildPageable();
		Page<Lessee> page = null;
		if(form.getId() == null) {
			page = lesseeDAO.findAll(pageable);			
		}else {
			page = lesseeDAO.findAll(form.buildSpes(), pageable);
		}
		HashMap<String , Object> result = DataGridUtils.getPageResult(page);
		return result;
	}

	/**
	 * 新增授权
	 * @param model
	 * @return
	 * @throws ParseException 
	 */
	/*@RequestMapping(value="save")
	@ResponseBody
	public String save(Lessee model,float cost) {
		SysUser user = userUtils.getUser();
		LesseeAdmin lesseeAdmin = lesseeAdminDAO.findById(user.getId());
		model.setLesseeAdmin(lesseeAdmin);
		lesseeDAO.save(model);

		Accredit accredit = new Accredit();
		Date date = new Date();
		accredit.setLessee(model);
		accredit.setMonth(12);
		accredit.setCost(cost);
		accredit.setBeginDate(date);
		Date newDate = stepMonth(date, 12);
		accredit.setOverDate(newDate);
		accService.save(accredit);
		return "ok";
	}*/
	//添加授权
		@RequestMapping(value="/save")
		@ResponseBody
		public Object save(AccreditForm2 form ,Integer lessee) throws ParseException {
			Lessee less = lesseeDAO.findById(lessee);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Accredit model=new Accredit();
			model.setBeginDate(sdf.parse(form.getBeginDate()));
			Date utilDate = sdf.parse(form.getBeginDate());   //把时间字符串转为date类型
			Date newDate =stepMonth(utilDate, form.getMonth());
			model.setLessee(less);
			model.setMonth(form.getMonth());
			model.setOverDate(newDate);
			model.setCost(form.getCost());
			accService.save(model);

			SysUser user = userUtils.getUser();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			String date = df.format(new Date());
			Journal journal = new Journal();
			journal.setDate(date);
			journal.setUsername(user.getUsername());
			journal.setOperationName("添加授权");
			service.save(journal);
			return "ok";
		}
/*	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(Accredit model) {
		Date newDate = stepMonth(model.getBeginDate(), model.getMonth());
		model.setOverDate(newDate);
		accService.save(model);
		return "ok";
	}*/

	/**
	 * 添加默认天数
	 * @param sourceDate
	 * @param month
	 * @return
	 */
	public static Date stepMonth(Date sourceDate, int month) {
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH, month);
        return c.getTime();
    }
	
	@RequestMapping(value="/deleteZh")
	@ResponseBody
	public void deleteZh(String ids) {
		SysUser user = userUtils.getUser();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String date = df.format(new Date());
		Journal journal = new Journal();
		journal.setDate(date);
		journal.setUsername(user.getUsername());
		journal.setOperationName("删除了租户");
		service.save(journal);
		String[] id = ids.split(",");
		for(int i = 0; i < id.length; i++) {
			lesseeDAO.deleteById(Integer.parseInt(id[i]));
		}
	}
	
	
	/**
	 * 租户管理的显示所有租户，
	 * 只能对租户进行注册
	 * @return
	 */
	
	@RequestMapping(value="/lesseeALL")
	public String lesseeALL() {
		return "admin/lesseeALL";
	}
	@RequestMapping(value="/lesseeList")
	@ResponseBody
	public Object lesseeList(LesseeForm form) {
		Pageable pageable = form.buildPageable();
		Page<Lessee> page = null;
		if(form.getId() == null) {
			page = lesseeDAO.findAll(pageable);			
		}else {
			page = lesseeDAO.findAll(form.buildSpes(), pageable);
		}
		HashMap<String , Object> result = DataGridUtils.getPageResult(page);
		return result;
	}
	
	/**
	 * 添加授权
	 * @return
	 */
	@RequestMapping(value="/add")
	public String add(ModelMap map) {
		List<LesseeAdmin> all = lesseeAdminDAO.findAll();
		map.put("all", all);
		return "admin/zh_add";
	}
	
	@RequestMapping(value="savezh")
	@ResponseBody
	public String savezh(Lessee model,Integer lesseeAdmin_id) {
		LesseeAdmin admin = lesseeAdminDAO.findById(lesseeAdmin_id);
		model.setLesseeAdmin(admin);
		lesseeDAO.save(model);
		
		SysUser user = userUtils.getUser();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = df.format(new Date());
		Journal journal = new Journal();
		journal.setDate(date);
		journal.setUsername(user.getUsername());
		journal.setOperationName("注册租户");
		service.save(journal);
		return "ok";
	}

	
	@RequestMapping(value="/yan")
	public Boolean gly(String username, String password) {
		SysUser user = userUtils.getUser();
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		boolean f = false;
		if(username.equals(user.getUsername()) && encoder.matches(password,user.getPassword())) {
			f = true;
		}
		return f;
	}
	
	/**
	 * 租户管理员显示所有电子发票
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/dzfp")
	public String dzfp() {
		return "system/dzfp";
		
	}
	@RequestMapping(value="/listDzfp")
	@ResponseBody
	public Object list(InvoiceForm form) {
		Pageable pageable = form.buildPageable();
		Page<Invoice> page = invoiceService.findAll(pageable);
		HashMap<String, Object> result = DataGridUtils.getPageResult(page);
		return result;
	}
	
	/**
	 * 电子发票批量删除
	 * @param ids
	 */
	@RequestMapping(value="/deleteDzfp")
	@ResponseBody
	public void deleteDzfp(String ids) {
		String[] id = ids.split(",");
		for(int i = 0; i < id.length; i++) {
			invoiceService.deleteById(Integer.parseInt(id[i]));
		}
	}
	
	/**
	 * 找回密码
	 * @return
	 */
	@RequestMapping(value="/retrieve")
	public String retrieve() {
		return "admin/retrievePwd";
	}
	
	@RequestMapping(value="/yx")
	@ResponseBody
	public String yx(String username) {
		//建立邮件消息
		SimpleMailMessage mainMessage = new SimpleMailMessage();
		//发送者
		mainMessage.setFrom(mailusername);
		//接收者
		mainMessage.setTo(username);
		//发送的标题
		mainMessage.setSubject("qq邮箱通知找回密码功能");
		String code = VerifyCodeUtils.generateVerifyCode(6);
		//发送的内容
		mainMessage.setText("请记住验证码："+code);
		jms.send(mainMessage);
		System.out.println("验证码"+code);
		return code;
	}
	
	@RequestMapping(value="/username")
	@ResponseBody
	public Boolean username(String username) {
		SysUser user = userDAO.findByUsername(username);
		if(user == null) {
			return false;
		}else {
			return true;
		}
	}
	@RequestMapping(value="/zhmm1")
	@ResponseBody
	public String zhmm1(String username, String password) {
		SysUser user = userDAO.findByUsername(username);
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		user.setPassword(encoder.encode(password));
		userDAO.save(user);
		return "密码找回成功！";
	}


}
